const express = require('express');
const router = express.Router();
const multer = require('multer');

const storage = multer.diskStorage({
    // 定义上传文件夹路径
    destination: function (req, file, cb) {
        cb(null, 'data/upload');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '_' + file.originalname);
    }
});
/**
 * @swagger
 * tags:
 *   name: File
 *   description: 文件上传接口
 */

/**
 * @swagger
 * /file:
 *   post:
 *     summary: 上传文件
 *     description: 接收单个文件的上传请求，并返回文件的存储路径。
 *     tags: [File]
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *                 description: 上传的文件。
 *     responses:
 *       200:
 *         description: 文件上传成功，并返回文件的访问路径。
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 状态码
 *                   example: 200
 *                 file:
 *                   type: object
 *                   properties:
 *                     url:
 *                       type: string
 *                       description: 上传文件的相对路径。
 *                       example: "/upload/1695892323492_filename.png"
 *       400:
 *         description: 上传失败，返回错误提示信息。
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   description: 状态码
 *                   example: 400
 *                 message:
 *                   type: string
 *                   description: 错误信息。
 *                   example: "文件上传失败"
 */
const upload = multer({ storage: storage });

router.post('', upload.single('file'), (req, res, next) => {
    const { file } = req;
    if (!file) {
        return res.status(400).send({ code: 400, message: '文件上传失败' });
    }
    const url = file.path.split('data')[1];
    res.status(200).send({ code: 200, file: { url } });
});

module.exports = router;
